﻿using System.Reflection;
using System.Runtime.Loader;
using FileDownLoadSystem.Core.Extensions;
using FileDownLoadSystem.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyModel;

namespace FileDownLoadSystem.Core.EfDbContext;

public class FileDownloadSystemDbContext : DbContext, IDependency
{
    public FileDownloadSystemDbContext()
    {
    }

    public FileDownloadSystemDbContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            optionsBuilder.UseMySql("Server=localhost;database=FileDownloadSystemDb;uid=root;pwd=1q2w3x;",
                MySqlServerVersion.LatestSupportedServerVersion);
        }

        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        try
        {
            // 获取所有的类库
            // DependencyContext依赖Microsoft.Extensions.DependencyModel包
            var compilationLibraries = DependencyContext.Default.CompileLibraries
                .Where(x => !x.Serviceable && x.Type != "package" && x.Type == "project");
            // 获取所有数据库模型
            foreach (var compilationLibrary in compilationLibraries)
            {
                // 加载指定类型
                AssemblyLoadContext.Default
                    .LoadFromAssemblyName(new AssemblyName(compilationLibrary.Name))
                    .GetTypes()
                    .Where(x =>
                        x.GetTypeInfo().BaseType != null
                        && !x.IsAbstract
                        && x.BaseType == (typeof(BaseModel)))
                    .ToList().ForEach(t => { modelBuilder.Entity(t); });
            }
        }
        catch (Exception e)
        {
        }

        base.OnModelCreating(modelBuilder);
    }
}